import { Account } from '@/common/web3/webMethods';
import HeaderComponent from '@/components/HeaderComponent/HeaderComponent';

import { Input, Toast } from 'antd-mobile';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { preRecharge, recharge } from '@/api/module/transaction';
import { getApiToken } from '@/api/module/U2U';
import Web3 from 'web3';
import { useAppDispatch } from '@/hooks/useAppDispatch';
import { fetchUserInfo } from '@/store/slices/userInfo';
import { useAppSelector } from '@/hooks/useAppSelector';
import { CenterPopupComponent } from '@/components/CenterPopupComponent/CenterPopupComponent';

const AssetsComponent = () => {
  const { t } = useTranslation();
  const userInfo = useAppSelector((state) => state.userInfo.userInfo);

  return (
    <div className="mt-4">
      <div className="flex items-center justify-between asstest mx-2 bg-bg-1 py-4 px-4 rounded-xl"></div>
      <div className="value text-white-1 py-12 px-5 bg-custom-gradient-1 rounded-xl relative -top-4 flex items-center justify-center">
        <span className="opacity-50">{t('USDTBanlance')}</span>
        <span className="ml-4 font-bold text-2xl">
          ${userInfo.USDT.balance}
        </span>
      </div>
    </div>
  );
};
const FormComponent = () => {
  const { t } = useTranslation();
  const [value, setValue] = useState('');
  const [password, setPassword] = useState('');
  const recAccount = '0x508e1E6D3aDf48c0Ddfa87f605629AED1c39e44D';
  const dispatch = useAppDispatch();

  const confirm = async () => {
    console.log(value, password);
    try {
      const preRes = await preRecharge({
        amount: value,
        currency: 'USDT',
        APITOKEN: APIToken,
      });
      setAPIToken('');
      console.log(preRes.code);
      if (preRes.code == 0) {
        console.log('shdkas', preRes.data.to_addr);
        const res = await Account.cTokens['USDT'].cTransfer(
          preRes.data.to_addr,
          preRes.data.amount,
          (hash: string) => {
            recharge({
              order_sn: preRes.data.order_sn + '',
              hash,
            }).then((res) => {
              setValue('');
              setPassword('');
              Toast.show({
                content: res.msg,
              });
            });
          }
        );
        console.log(res);
      } else {
        Toast.show({
          content: preRes.msg,
        });
      }
    } catch (error) {
      console.log(error);
      setVisible(false);
      setAPIToken('');
      const initStr = /cTransfer/g;
      const errMsg = String(error);
      if (errMsg.match(initStr)) {
        const web3 = new Web3((window as any).ethereum);
        await Account.init(web3);
        // 添加代币
        await Account.addCToken('USDT');
        // webStore.setAddress()
        dispatch(fetchUserInfo());
        alert(t('authSuccessful'));
        // @ts-ignore
      } else if (error.code == 4001) {
        Toast.show({
          content: t('transactionFailed'),
        });
      } else {
        Toast.show({
          content: t(error as string),
        });
      }
    }
  };

  const [visible, setVisible] = useState(false);
  const [APIToken, setAPIToken] = useState('');
  const reqApiToken = async () => {
    try {
      if (!value) {
        Toast.show({
          content: t('enterCompleteInformation'),
        });
        return;
      }
      // if (!password) {
      //   Toast.show({
      //     content: '请输入2FA OTP',
      //   });
      //   return;
      // }
      if (!APIToken) {
        const res = await getApiToken();
        setAPIToken(res.data.api_token);
      }

      setVisible(true);
    } catch (error) {
      console.log(error);
    }
  };
  return (
    <div
      className="mt-4"
      style={{
        fontSize: '95%',
      }}
    >
      <div className="number">
        <div>{t('rechargeNumber')}</div>
        <div className="bg-bg-1 py-4 mt-3 px-3 rounded-lg flex items-center">
          <span className="font-bold text-lg">$</span>
          <Input
            min={1}
            type="number"
            style={{
              '--font-size': '14px',
              '--color': '#fff',
            }}
            className="ml-2"
            placeholder={`${t('enter')}`}
            value={value}
            onChange={(val) => {
              setValue(val);
            }}
          />
        </div>
      </div>
      {/* <div className="password mt-4">
        <div>{t('password')}</div>
        <Input
          style={{
            '--font-size': '14px',
            '--color': '#fff',
          }}
          type="password"
          className="bg-bg-1 py-4 mt-3 px-3 rounded-lg "
          placeholder={`${t('enter')}`}
          value={password}
          onChange={(val) => {
            setPassword(val);
          }}
        />
      </div> */}
      <div
        onClick={reqApiToken}
        className="mt-6 bg-bg-16 py-4 round
        ed-md text-center text-base"
      >
        {t('confirm')}
      </div>
      <CenterPopupComponent
        visible={visible}
        setVisible={setVisible}
        title="recharge"
        content={`${t('recharge')}${value}USDT`}
        onClick={() => confirm()}
      />
    </div>
  );
};
export default function Recharge() {
  return (
    <div className="text-white-1 px-4">
      <HeaderComponent
        title="recharge"
        centerStyle={{
          fontSize: '18px',
        }}
      />
      <AssetsComponent />
      <FormComponent />
    </div>
  );
}
